package com.rainng.coursesystem.manager.admin;

import com.rainng.coursesystem.dao.AreaDAO;
import com.rainng.coursesystem.dao.ActivityDAO;
import com.rainng.coursesystem.dao.LeaderDAO;
import com.rainng.coursesystem.manager.BaseManager;
import com.rainng.coursesystem.model.entity.AreaEntity;
import com.rainng.coursesystem.model.vo.response.IdNameVO;
import com.rainng.coursesystem.model.vo.response.table.AreaItemVO;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Component
public class AreaManager extends BaseManager {
    private final AreaDAO areaDAO;
    private final LeaderDAO leaderDAO;
    private final ActivityDAO activityDAO;

    public AreaManager(AreaDAO areaDAO, LeaderDAO leaderDAO, ActivityDAO activityDAO) {
        this.areaDAO = areaDAO;
        this.leaderDAO = leaderDAO;
        this.activityDAO = activityDAO;
    }

    public Integer getPageCount(String name) {
        int count = areaDAO.count(name);
        return calcPageCount(count, AreaDAO.PAGE_SIZE);
    }

    @Transactional
    public List<AreaItemVO> getPage(Integer index, String namePart) {
        List<AreaItemVO> areaItemList = new ArrayList<>();
        List<AreaEntity> areaList = areaDAO.getPage(index, namePart);

        for (AreaEntity area : areaList) {
            int id = area.getId();
            String name = area.getName();
            int activityCount = activityDAO.countByAreaId(id);
            int leaderCount = leaderDAO.countByAreaId(id);

            areaItemList.add(new AreaItemVO(id, name, activityCount, leaderCount));
        }

        return areaItemList;
    }

    public AreaEntity get(Integer id) {
        return areaDAO.get(id);
    }

    public int create(AreaEntity entity) {
        return areaDAO.insert(entity);
    }

    public int update(AreaEntity entity) {
        return areaDAO.update(entity);
    }

    public int delete(Integer id) {
        return areaDAO.delete(id);
    }

    public boolean hasActivity(Integer id) {
        return activityDAO.countByAreaId(id) > 0;
    }

    public boolean hasLeader(Integer id) {
        return leaderDAO.countByAreaId(id) > 0;
    }

    public List<IdNameVO> listName() {
        List<IdNameVO> voList = new ArrayList<>();
        List<AreaEntity> entityList = areaDAO.listName();
        for (AreaEntity entity : entityList) {
            voList.add(new IdNameVO(entity.getId(), entity.getName()));
        }

        return voList;
    }
}
